package com.java.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.study.common.utils.*;
import com.java.study.config.WechatConfig;
import com.java.study.dao.UserDao;
import com.java.study.dao.VideoDao;
import com.java.study.dao.VideoOrderDao;
import com.java.study.dto.VideoOrderDto;
import com.java.study.entity.UserEntity;
import com.java.study.entity.VideoEntity;
import com.java.study.entity.VideoOrderEntity;
import com.java.study.service.VideoOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;


@Service("videoOrderService")
public class VideoOrderServiceImpl extends ServiceImpl<VideoOrderDao, VideoOrderEntity> implements VideoOrderService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private VideoDao videoDao;
	@Autowired
	private WechatConfig wechatConfig;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<VideoOrderEntity> page = this.page(
				new Query<VideoOrderEntity>().getPage(params),
				new QueryWrapper<VideoOrderEntity>()
		);

		return new PageUtils(page);
	}

	@Override
	@Transactional
	public String save(VideoOrderDto videoOrderDto) throws Exception {
		//查找视频信息
		VideoEntity video = videoDao.selectById(videoOrderDto.getVideoId());
		//查找用户信息
		UserEntity user = userDao.selectById(videoOrderDto.getUserId());
		if (video == null || user == null) {
			return null;
		}

		//生成订单
		VideoOrderEntity videoOrder = new VideoOrderEntity();
		videoOrder.setTotalFee(video.getPrice());
		videoOrder.setVideoImg(video.getCoverImg());
		videoOrder.setVideoTitle(video.getTitle());
		videoOrder.setCreateTime(new Date());
		videoOrder.setVideoId(video.getId());
		videoOrder.setState(0);
		videoOrder.setUserId(user.getId());
		videoOrder.setHeadImg(user.getHeadImg());
		videoOrder.setNickname(user.getName());

		videoOrder.setDel(0);
		videoOrder.setIp(videoOrderDto.getIp());
		videoOrder.setOutTradeNo(CommonUtils.generateUUID());

		//保存订单
		this.baseMapper.insert(videoOrder);

		//获取codeurl
		return unifiedOrder(videoOrder);
	}

	/**
	 * 统一下单方法
	 */
	private String unifiedOrder(VideoOrderEntity videoOrder) throws Exception {

		//生成签名
		SortedMap<String, String> params = new TreeMap<>();
		params.put("appid", wechatConfig.getAppid());
		params.put("mch_id", wechatConfig.getMchId());
		params.put("nonce_str", CommonUtils.generateUUID());
		params.put("body", videoOrder.getVideoTitle());
		params.put("out_trade_no", videoOrder.getOutTradeNo());
		params.put("total_fee", videoOrder.getTotalFee().toString());
		params.put("spbill_create_ip", videoOrder.getIp());
		params.put("notify_url", wechatConfig.getPayCallbackUrl());
		params.put("trade_type", "NATIVE"); //扫码支付

		//sign签名
		String sign = WXPayUtil.createSign(params, wechatConfig.getKey());
		params.put("sign", sign);

		//map转xml
		String payXml = WXPayUtil.mapToXml(params);

		//统一下单
		String orderStr = OKHttpUtil.httpPost(WechatConfig.UNIFIED_ORDER_URL,payXml);
		if(null == orderStr) {
			return null;
		}

		Map<String, String> unifiedOrderMap =  WXPayUtil.xmlToMap(orderStr);
		if(unifiedOrderMap != null) {
			return unifiedOrderMap.get("code_url");
		}
		return null;
	}
}